import {RequestOptions} from '@@/plugin-request/request';
import {AppConfig} from '@/core/configs/app.config';
import {AxiosResponse} from 'axios';

export const AuthorizationInterceptor = {
    requestInterceptor: (config: RequestOptions) => {
        const cacheData = window.sessionStorage.getItem(AppConfig.AUTHORIZATION_TOKEN);
        const JwtToken = cacheData ? JSON.parse(cacheData) : null;
        if (JwtToken) {
            config.headers = {...config.headers, authorization: JwtToken};
        }
        return config;
    },
    responseInterceptors: (response: AxiosResponse) => {
        console.log(response)
        //请求成功处理数据格式
        if (response.data.success) {
            //统一请求拿到的数据格式
            response.data = response.data.data;
            // 读取鉴权信息，放入缓存中
            const JwtToken = response.headers[AppConfig.AUTHORIZATION_TOKEN];
            if (JwtToken) {
                window.sessionStorage.setItem(AppConfig.AUTHORIZATION_TOKEN, JSON.stringify(JwtToken));
                window.sessionStorage.setItem(AppConfig.AUTHORIZATION_TIME, new Date().getTime().toString());
            }
        }
        return response;
    },
};


